"""
httpserver 1.0 版本
    要求:1. 获取来自浏览器的请求
        2. 判断请求内容是/将index.html返回客户端
        3. 如果请求的是其他内容则返回404
"""
from socket import *
def response(conf,number):
    # 将请求内容提取出来
    # 判断是"/" 返回 index.html
    # 如果不是则返回404
    data=conn.recv(number)
    if not data:
        return
    info=data.decode().split()[1]
    abnormal_request="""HTTP/1.1 404 NOT FOUND\r\nContent-Type: text/html\r\n
    <h1>404 Not Found</h1>"""
    with open("index.html",encoding="utf-8") as f:
        # normal_request="HTTP/1.1 200 OK\r\n"+"Content-Type: text/html\r\n"+"\r\n"+f.read()
        normal_request="""HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\n"""+f.read()
    if info=='/':
        return normal_request
    else:
        return abnormal_request

server=socket(AF_INET,SOCK_STREAM)
server.bind(("127.0.0.1",8888))
server.listen(15)
while True:
    print("等待连接")
    conn,addr = server.accept()
    print(addr,"已连接")
    conn.send(response(conn,4096).encode())
